<script lang="ts" setup>
import { reactive, ref, Ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useMessage } from '/@/hooks/web/useMessage';

import MenuDrawer from './MenuDrawer.vue';
import AddRoleModal from './AddRoleModal.vue';
import BindedUserModal from './BindedUserModal.vue';
import UnbindUserModal from './UnbindUserModal.vue';

import { getRoleList, deleteRole, updateRoleResource, } from '/@/api/role';
import { Icon } from '/@/components/Icon';

const { createMessage } = useMessage();
const state = reactive({
  loading: false,
});

const searchFormRef = ref();
const searchForm = reactive({ userName: '' });
const searchFormActions = {
  async onSearch() {
    tableActions.getList();
  },
  resetFields(formRef) {
    formRef.resetFields();
    pgActions.resetPg();
    tableActions.getList();
  },
};

const table = reactive({
  data: [],
  selected: [] as any,
});

interface IRole {
  roleId: number;
  [p: string]: any;
}
const tableActions = {
  selectionChange(v) {
    table.selected = v;
  },
  async getList() {
    let params = {
      startIndex: pg.current,
      pageSize: pg.size,
      roleName: searchForm.userName,
    };
    state.loading = true;
    let { data: ret, code, msg } = await getRoleList(params);
    state.loading = false;
    if (code === 200) {
      table.data = ret.list || [];
      table.selected = [];
      pg.total = ret.total;
    } else {
      createMessage({
        message: msg,
        type: 'error',
      });
    }
  },
  create() {
    modal.data = undefined;
    modalActions.show();
  },
  update(r) {
    modal.data = r;
    modalActions.show();
  },
  updateMenus(r) {
    console.log('r', r);
    menuModal.data = r;
    menuModalActions.show();
  },
  delete(r) {
    deleteReq([r.id]);
  },
  batchDel() {
    let ids = table.selected.map((e) => e.id);
    deleteReq([...ids]);
  },

  bindUser(r) {
    console.log('ru', r);
    modal4.data = r;
    modal4Actions.show();
  },

  bindedUser(r) {
    userModal.data = r;
    userModalActions.show();
  },
};

const pg = reactive({
  current: 1,
  size: 20,
  total: 0,
});

const pgActions = {
  resetPg: () => {
    pg.current = 1;
    pg.size = 20;
    pg.total = 0;
  },
  currentChange(r) {
    pg.current = r;
    searchFormActions.onSearch();
  },
  sizeChange(r) {
    pg.current = 1;
    pg.size = r;
    searchFormActions.onSearch();
  },
};

const modal = reactive({
  visible: false,
  data: undefined,
});

const modalActions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    modal.visible = true;
  },
};

const dataModal = reactive({
  visible: false,
  data: undefined as any,
});

const dataModalActions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    dataModal.visible = true;
  },
};
const menuModal = reactive({
  visible: false,
  data: undefined as any,
});

const menuModalActions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    menuModal.visible = true;
  },
};

const userModal = reactive({ data: undefined as any, visible: false });
const userModalActions = {
  show() {
    userModal.visible = true;
  },
  success() { },
};
const modal4 = reactive({ data: undefined as any, visible: false });
const modal4Actions = {
  show() {
    modal4.visible = true;
  },
  success() { },
};
const modal5 = reactive({ data: undefined as any, visible: false });
const modal5Actions = {
  show() {
    modal5.visible = true;
  },
  async success(resourceSelected) {
    state.loading = true;
    const { respCode, respMsg } = await updateRoleResource({
      roleId: modal5.data.roleId,
      clientManagerIds: resourceSelected
    });
    state.loading = false;
    if (respCode == 200) {
      createMessage({ message: respMsg })
      tableActions.getList();
    }
  },
};
// req
async function deleteReq(p) {
  state.loading = true;
  const { code, msg } = await deleteRole({ ids: p });
  state.loading = false;
  if (code == 200) {
    createMessage({
      message: msg,
    });
    searchFormActions.onSearch();
  }
}

searchFormActions.onSearch();
// const roleTagList = ref([]) as Ref<Array<any>>;
// const getGroupTagsAction = async () => {
//   const { respCode, data } = await getDictData({ dictCode: ' ziam_role_tag' });
//   if (respCode == 200) {
//     roleTagList.value = data.map((e) => ({
//       label: e.name,
//       value: e.value,
//     }));
//     searchFormActions.onSearch();
//   }
// };
// getGroupTagsAction();

// 控制哪些行可以选择
const unmodifiableRoleCodes = ['101', '102', '103']
const isSelectable = (row: any) => {
  return !unmodifiableRoleCodes.includes(row.roleCode)
}
const isEditable = (row: any) => {
  return unmodifiableRoleCodes.includes(row.roleCode)
}
</script>

<template>
  <div class="p-4 role-managment">
    <div class="searchBox px-4 pt-4">
      <el-form label-width="70px" :model="searchForm" ref="searchFormRef" inline>
        <el-form-item prop="userName" label="角色名称">
          <el-input placeholder="请输入角色名称" v-model="searchForm.userName" clearable />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" :loading="state.loading" @click="searchFormActions.onSearch">查询</el-button>
          <el-button @click="searchFormActions.resetFields(searchFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="middle-content p-4">
      <div class="tools mb-4">
        <div class="toolBtns">
          <el-button type="primary" @click="tableActions.create">
            <PlusOutlined />新建
          </el-button>
          <el-popconfirm title="此操作会解除所有绑定关系，确定删除吗？" @confirm="tableActions.batchDel" confirm-button-text="确定"
            cancel-button-text="取消">
            <template #reference>
              <el-button link :disabled="table.selected.length == 0">
                <Icon icon="ep:delete" />批量删除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <div class="selected">
          已选择<span class="blue">{{ table.selected.length }} 项</span>
        </div>
      </div>
      <el-table class="mb-4" v-loading="state.loading" :data="table.data" @selection-change="tableActions.selectionChange" row-key="id" :header-cell-style="{ background: '#f1f3f7' }">
        <el-table-column type="selection" width="55" fixed :selectable="isSelectable" />
        <el-table-column prop="roleName" label="角色名称" :width="220" fixed show-overflow-tooltip />
        <el-table-column prop="roleCode" label="角色编号" :width="220" show-overflow-tooltip />
        <!-- <el-table-column prop="tag" label="标签" :width="220">
          <template #default="scope">
            <span class="label" v-if="scope.row.tag">
              {{ roleTagList.filter((e) => e.value == scope.row.tag)[0].label }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column prop="clientName" label="所属应用" :width="220" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row?.clientModel?.clientName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" :width="120" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="operation" label="操作" :width="320" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="tableActions.updateMenus(scope.row)">菜单
            </el-button>
            <el-button link type="primary" @click="tableActions.bindedUser(scope.row)">已有用户
            </el-button>
            <el-button link type="primary" @click="tableActions.bindUser(scope.row)">新增用户
            </el-button>
            <el-button link type="primary" @click="tableActions.update(scope.row)" :disabled="isEditable(scope.row)">编辑 </el-button>
            <el-popconfirm title="此操作会解除所有绑定关系，确定删除吗？" @confirm="tableActions.delete(scope.row)"
              confirm-button-text="确定" cancel-button-text="取消">
              <template #reference>
                <el-button link type="danger" :disabled="isEditable(scope.row)">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="flex justify-end" background layout="total, sizes, prev, pager, next" :total="pg.total"
        :current-page="pg.current" v-model:page-size="pg.size" @size-change="pgActions.sizeChange"
        @current-change="pgActions.currentChange" :page-sizes="[20, 30, 50]" />
    </div>
    <AddRoleModal v-model:visible="modal.visible" :data="modal.data"
      @success="modalActions.success" />
    <MenuDrawer 
      v-model:visible="menuModal.visible" 
      :roleId="menuModal.data?.id" 
      @success="modalActions.success"
    />
    <BindedUserModal v-model:visible="userModal.visible" :roleId="userModal.data?.id"
      @success="userModalActions.success" />
    <UnbindUserModal v-model:visible="modal4.visible" :roleId="modal4.data?.id" @success="modal4Actions.success" />
  </div>
</template>

<style lang="less" scoped>
html[data-theme='light'] {

  .searchBox,
  .middle-content {
    background-color: #fff;
  }
}

html[data-theme='dark'] {

  .searchBox,
  .middle-content {
    background-color: #151515;
  }
}

.role-managment {
  min-height: 100%;
  display: flex;
  flex-direction: column;

  .middle-content {
    flex: 1;

    .tools {
      display: flex;
      justify-content: space-between;

      .selected {
        line-height: 32px;

        .blue {
          margin-left: 5px;
          color: #237ae4;
        }
      }
    }
  }

  :deep(.label) {
    font-size: 12px;
    border: 1px solid rgb(58, 173, 68);
    background-color: rgba(58, 173, 68, 0.1);
    color: rgb(58, 173, 68);
    border-radius: 3px;
    padding: 3px 8px;
    margin-left: 25px;
  }
}
</style>
